<template>
	<view class="container">
		<!-- 现有成员 -->
		<view class="section">
			<view class="section-title">
				<view class="member_norm" :class="{'member-vote':selctVote===false}" @click="selctVote=false">现有成员</view>
				<view class="member_norm"  :class="{'member-vote':selctVote===true}" @click="selctVote=true">黑名单</view>
				</view>
		
			<view class="member-list">
				<view class="member-item" v-for="(item, index) in groupUserShow" :key="index">
					<view class="member-info">
						<view class="avatar-box"><image class="avatar" :src="item.nicPic" mode="aspectFill"></image>
						<view v-if="item.isTemp" class="dot">临时</view>
						</view>
						
						<view class="user-details">
							<view class="display-name">
							<text class="" style="font-weight: 500;">{{item.nicName }}</text>
							<text class="" style="color: blue;" v-if="item.remarkName">备注名：{{item.remarkName}}</text>
						</view>
						
							<text class="user-id">ID: {{ item.userId }}</text>
							<text class="mute-status" v-if="item.isVote">(已踢出)</text>
							<text class="mute-status" v-else-if="item.isMuted">（已禁言）</text>
							
						</view>
					</view>
					<view class="member-actions">
						<uni-icons type="more" size="24" @click="showMemberActions(index)"></uni-icons>
					</view>
				</view>
			</view>
		</view>

		<!-- 附近用户 -->
		<view class="section">
			<view class="section-title">附近用户{{ newMembers.length }}人</view>
			<view class="member-list">
				<view class="member-item" v-for="(item, index) in newMembers" :key="'new' + index">
					<view class="member-info">
						<image class="avatar" :src="item.nicPic" mode="aspectFill"></image>
						<view class="user-details">
							<text class="display-name">{{ item.userId }}</text>
							<text class="distance">{{ distance(item) }}</text>
						</view>
					</view>
					<view class="member-actions">
						<text v-if="isMebers(item.userId)" class="member-status">已是成员</text>
						<button v-else class="btn-add" @click="addMember(index)">添加</button>
						<uni-icons type="compose" size="24" @click="showRemarkDialog(item)"></uni-icons>
					</view>
				</view>
			</view>
		</view>

		<!-- 备注弹窗 -->
		<uni-popup ref="remarkPopup" type="dialog">
			<uni-popup-dialog mode="input" title="设置备注" :value="currentRemark" @confirm="confirmRemark"></uni-popup-dialog>
		</uni-popup>
	</view>
</template>

<script>
import { map } from 'lodash-es';
import {distance_m} from'../../utils/distance'

const app = getApp().globalData;
	const db = uniCloud.databaseForJQL();
export default {
	data() {
		return {
			user: {},
			groupUser: [],
			newMembers: [],
			radius: 500,
			currentMemberIndex: -1,
			currentRemark: '',
			currentMemberId: '',
			groupId:"",
			selctVote:false
		};
	},
    computed:{
		groupUserShow(){
			return this.groupUser.filter(item=>item.isVote===this.selctVote)
		}
	},
	onLoad(res) {
		if (!app || !app.user) {
			console.error('用户信息未定义');
			uni.showToast({ title: '用户信息加载失败', icon: 'none' });
			return;
		}
		this.groupId=res.groupId
		this.user = app.user;
		this.getMembers();
		this.getNearByUser()
	},
	methods: {
		// 显示成员操作菜单
		showMemberActions(index) {
			if (index < 0 || index >= this.groupUser.length) {
				uni.showToast({ title: '无效的成员索引', icon: 'none' });
				return;
			}
			uni.showActionSheet({
				itemList: ['禁言/解禁', '踢出/重拉', '设置备注', '设置事项'],
				success: (res) => {
					switch (res.tapIndex) {
						case 0:
							this.toggleMute(index);
							break;
						case 1:
							this.removeMember(index);
							break;
						case 2:
							this.showRemarkDialog(this.groupUser[index]);
							break;
						case 3:
							// 设置事项逻辑
							break;
					}
				}
			});
		},
		distance(item) {
			const location={
				longitude:item.location.coordinates[0],
				latitude:item.location.coordinates[1]
			}
		
		return   distance_m(app.senderLocation,location)	
		},
		
		async toggleMute(index) {
			if (index < 0 || index >= this.groupUser.length) {
				uni.showToast({ title: '无效的成员索引', icon: 'none' });
				return;
			}
			const member = this.groupUser[index];
		
			try {
			// 先更新本地数据
				const updatedGroupUser = this.groupUser.map((u) => {
					if (u.userId === member.userId) {
						return { ...u, isMuted: !u.isMuted };
					}
					return u;
				});

				// 立即更新视图
				this.groupUser = [...updatedGroupUser];
				const Imember=this.groupUser.map(u=>u.userId===app.user.userId)
				// 提交数据库更新
				const updateRes = await db
					.collection('Group')
					.where({
						'groupId': this.groupId
					})
					.update({
						groupUser: updatedGroupUser
					});
				if (updateRes.updated === 0) {
					throw new Error('数据库更新失败');
				}
				uni.showToast({ title: '操作成功' });
			} catch (e) {
				// 回滚本地状态
				this.groupUser = [...this.groupUser];
				console.error('禁言/解禁操作失败:', e);
				uni.showToast({ title: '操作失败', icon: 'none' });
			}
		},
		async removeMember(index) {
			if (index < 0 || index >= this.groupUser.length) {
				uni.showToast({ title: '无效的成员索引', icon: 'none' });
				return;
			}
			const member = this.groupUser[index];
			const updatedGroupUser = this.groupUser.map((u) => {
				if (u.userId === member.userId) {
					return { ...u, isVote: !u.isVote };
				}
				return u;
			});
			
	  uni.showModal({
				title: '确认踢出/重拉',
				content: `确定要踢出/重拉 ${member.remarkName || member.userId} 吗？`,
				success: async (res) => {
					if (res.confirm) {
						try {
							const db = uniCloud.databaseForJQL();
							const updateRes = await db
								.collection('Group')
								.where({
									'groupId': this.groupId
								})
								.update({
									groupUser: updatedGroupUser
								});
							if (updateRes.updated === 0) {
								throw new Error('数据库更新失败');
							}
							// 更新本地数据
						// 刷新附近用户状态
					 
							await this.getMembers();
							uni.showToast({ title: '踢出重拉成功' });
						} catch (e) {
							console.error('踢出/重拉成员失败:', e);
							uni.showToast({ title: '踢出/重拉失败', icon: 'none' });
						}
					}
				}
			});
		},
		async addMember(index) {
			if (index < 0 || index >= this.newMembers.length) {
				uni.showToast({ title: '无效的成员索引', icon: 'none' });
				return;
			}

			const newMember = this.newMembers[index];

			// 本地双重验证
			if (this.groupUser.some((u) => u.userId === newMember.userId) || this.newMembers[index].isMember) {
				uni.showToast({ title: '用户已在群组中', icon: 'none' });
				return;
			}

			uni.showModal({
				title: '确认添加',
				content: `添加用户 ${newMember.userId}？`,
				success: async (res) => {
					if (res.confirm) {
						try {
							const db = uniCloud.databaseForJQL();
							const groupRes = await db.collection('Group').where({ groupId: this.groupId }).get();

							if (groupRes.data.length === 0) {
								uni.showToast({ title: '未找到群组', icon: 'none' });
								return;
							}

							// 数据库验证
							const existingUsers = groupRes.data[0]?.groupUser || [];
							if (existingUsers.some((u) => u.userId === newMember.userId)) {
								uni.showToast({ title: '用户已存在', icon: 'none' });
								return;
							}

							// 执行更新
							const updateRes = await db
								.collection('Group')
								.doc(groupRes.data[0]._id)
								.update({
									groupUser: [
										...existingUsers,
										{
											userId: newMember.userId,
											nicPic: newMember.nicPic,
											userTel: newMember.userTel,
											nicName: newMember.nicName || newMember.userId,
											isTemp: false,
											isMember:true,
											joinTime: Date.now(),
											isMuted: false,
											remarkName: ''
										}
									]
								});
							if (updateRes.updated === 0) {
								throw new Error('数据库更新失败');
							}

							// 更新本地状态
							this.newMembers = this.newMembers.map((m) => (m.userId === newMember.userId ? { ...m, isMember: true } : m));
							await this.getMembers(); // 刷新完整数据
							uni.showToast({ title: '添加成功' });
						} catch (e) {
							console.error('添加成员失败:', e);
							uni.showToast({ title: '添加失败', icon: 'none' });
						}
					}
				}
			});
		},
		// 显示备注弹窗
		isMebers(userId){
		return this.groupUser.find(m => m.userId === userId);
		},
		
		
		showRemarkDialog(member) {
			if (!member) {
				uni.showToast({ title: '无效的成员信息', icon: 'none' });
				return;
			}
			this.currentRemark = member.remarkName || '';
			this.currentMemberId = member.userId;
			console.log("选择的ID",this.currentMemberId)
			this.$refs.remarkPopup.open();
		},
		// 确认备注
		async confirmRemark(value) {
			try {
				
				const groupRes = await db
					.collection('Group')
					.where({
						groupId:this.groupId
					})
					.get();

				if (groupRes.data.length === 0) {
					uni.showToast({ title: '未找到群组', icon: 'none' });
					return;
				}

				const groupDoc = groupRes.data[0];
				// 更新群组成员
				const updatedMembers = groupDoc.groupUser.map((u) => (u.userId === this.currentMemberId ? { ...u, remarkName: value } : u));

				const updateRes = await db.collection('Group').doc(groupDoc._id).update({
					groupUser: updatedMembers
				});
				if (updateRes.updated === 0) {
					throw new Error('数据库更新失败');
				}

				// 更新本地数据
				this.groupUser = this.groupUser.map((u) => (u.userId === this.currentMemberId ? { ...u, remarkName: value } : u));

				uni.showToast({ title: '备注设置成功' });
			} catch (e) {
				console.error('设置备注失败:', e);
				uni.showToast({ title: '备注设置失败', icon: 'none' });
			}
		},
		// 获取成员数据
		async getMembers() {
			if (!this.user || !this.user.userId) {
				console.error('用户信息不完整，无法获取成员数据');
				uni.showToast({ title: '用户信息不完整', icon: 'none' });
				return;
			}
		
			try {
				const groupRes = await db
					.collection('Group')
					.where({groupId:this.groupId })
					.field({
						groupUser: true,
						location: true
					})
					.get();

				if (groupRes.data.length === 0) {
					console.error('未找到群组数据');
					uni.showToast({ title: '未找到群组数据', icon: 'none' });
					return;
				}

				const groupData = groupRes.data[0];
				if (!groupData.groupUser || !groupData.location || !groupData.location.coordinates) {
					console.error('群组数据不完整');
					uni.showToast({ title: '群组数据不完整', icon: 'none' });
					return;
				}

				// 使用 Map 存储用户信息
				const memberMap = new Map();

				// 正确处理异步操作，使用 Promise.all
				const userPromises = groupData.groupUser.map(async (item) => {
					const res = await db
						.collection('linli-user')
						.where({
							userId: item.userId
						})
						.field({
							userId:true,
							nicName:true,
							nicPic:true,
							userTel:true
						})
						.get();

					if (res.data && res.data.length > 0) {
						// 合并用户信息
						const mergedUser = { ...item, ...res.data[0] };
						memberMap.set(item.userId, mergedUser);
						return mergedUser;
					}
					return null; // 用户不存在的情况
				});

				// 等待所有用户信息查询完成
				const userList = (await Promise.all(userPromises)).filter(Boolean);

				// 更新组件数据
				this.groupUser = userList;
				console.log("群成员",this.groupUser);
			} catch (error) {
				console.error('获取群组用户信息失败', error);
				uni.showToast({ title: '获取数据失败', icon: 'none' });
			}
		},
		//获取附近用户
	async getNearByUser() {
	  try {
	    const data = {
	      type: 'getNearByInfo',
	      location: app.location,
	      radius: 5
	    };
	
	    const membersRes = await uniCloud.callFunction({
	      name: 'web',
	      data: data
	    });
	
	    // 检查云函数调用是否成功
	    if (!membersRes || !membersRes.result || !membersRes.result.onlineUsers) {
	      console.error('云函数返回格式异常:', membersRes);
	      uni.showToast({ title: '获取附近用户失败', icon: 'none' });
	      return;
	    }
	
	    const onlineUsers = membersRes.result.onlineUsers.data;
	    
	    // 修正 map 函数，正确返回包含 userId 和 location 的对象
	
	    const userLocations = onlineUsers.map(item => ({
	      userId: item.userId,
	      location: item.location
	    }));

	  const userPromises = userLocations.map(async (item) => {
	  	const res = await db
	  		.collection('linli-user')
	  		.where({
	  			userId: item.userId
	  		})
	  		.field({
	  			userId:true,
	  			nicName:true,
	  			nicPic:true,
	  			userTel:true
	  		})
	  		.get();
	  
	  	if (res.data && res.data.length > 0) {
	  		// 合并用户信息
	  		const mergedUser = { ...item, ...res.data[0] };
	  	
	  		return mergedUser;
	  	}
	  	return null; // 用户不存在的情况
	  });
	  
	  // 等待所有用户信息查询完成
	  const userList = (await Promise.all(userPromises)).filter(Boolean);
	  
	  // 更新组件数据
	  this.newMembers = userList
  
	  } catch (error) {
	    console.error('调用云函数失败:', error);
	    uni.showToast({ title: '获取附近用户失败', icon: 'none' });
	  }
	}
	}
};
</script>

<style scoped>
.container {
	padding: 20rpx;
}

.section-title {
     display: flex;
	 justify-content: space-between;
	font-size: 32rpx;
	font-weight: bold;
	margin: 20rpx 0;
	color: #333;
	padding-left: 20rpx;
	
}
.member_norm{
	display: flex;
	align-items: center;
	justify-content: center;
	width: 180rpx;
	height: 46rpx;
	border-radius: 23rpx;
	background-color: green;
	color: white;
	 background-color: #ccc;
}
.member-vote{
	   	background-color: green;
		color: white;
}
.member-list {
	background-color: #fff;
	border-radius: 16rpx;
	padding: 0 20rpx;
}

.member-item {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 24rpx 0;
	border-bottom: 1rpx solid #eee;
}

.member-info {
	flex: 1;
	display: flex;
	align-items: center;
}

.avatar {
	width: 80rpx;
	height: 80rpx;
	border-radius: 50%;
	margin-right: 20rpx;
}

.user-details {
	flex: 1;
	position: relative;
}

.display-name {
	font-size: 28rpx;
	color: #333;
	display: flex;
    gap: 20rpx;
	margin-bottom: 4rpx;
}

.user-id {
	font-size: 24rpx;
	color: #666;
}

.mute-status {
	color: #eb5757;
	font-size: 24rpx;
	margin-left: 10rpx;
}

.distance {
	font-size: 24rpx;
	color: #666;
}

.member-actions {
	display: flex;
	align-items: center;
	gap: 20rpx;
}

.btn-add {
	font-size: 24rpx;
	padding: 8rpx 20rpx;
	background-color: #007aff;
	color: white;
	border-radius: 40rpx;
}

.member-status {
	font-size: 24rpx;
	color: #999;
	padding: 8rpx 20rpx;
	border-radius: 40rpx;
	background-color: #f5f5f5;
}
.avatar-box{
	position: relative;
}
.dot{
	position: absolute;
	top:0;
	right: 0;
	width: 60rps;
	height: 20rpx;
	text-align: center;
	text-justify: auto;
	font-size: 20rpx;
	background-color: #007aff;
	color: #fff;
	border-radius: 3rpx;
}

</style>
